package user

import (
	"github.com/lzzyuhyy/framework/mysql"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Mobile   string `gorm:"type:char(11);unique:mobile;comment:手机号"`
	Nickname string `gorm:"type:varchar(255);comment:昵称"`
	Avatar   string `gorm:"type:varchar(255);comment:头像"`
	Status   int8   `gorm:"type:tinyint(1);default:0;comment: 0正常 1冻结"`
}

func CreatedUser(user *User) error {
	return mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Create(&user).Error
	})
}

func GetUserByMobile(user *User) error {
	return mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Where("mobile = ? and status = 0", user.Mobile).Limit(1).Find(&user).Error
	})
}

func GetUserInfoById(user *User) error {
	return mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Where("id = ? and status = 0", user.ID).Limit(1).Find(&user).Error
	})
}

func UpdateUserInfo(user *User) error {
	return mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Where("id = ?", user.ID).Limit(1).Updates(&user).Error
	})
}

// 用户刷题记录表
type UserAnswer struct {
	gorm.Model
	UserID       int64 `json:"user_id" gorm:"type:int(11);not null,index;comment:用户id"`
	PId          int64 `json:"p_id" gorm:"type:int(11);not null;default:0;comment('父分类id 一级分类值为0 二级分类为对应父级id')"`
	InterviewsId int64 `json:"interviews_id" gorm:"type:int(11);not null,index;comment:题目id"`
}

//用户刷题添加记录

func (Ua *UserAnswer) UserAnswerCreate() (err error) {
	return mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Create(&Ua).Error
	})
}

// 用户刷题记录列表
func (ua *UserAnswer) UserAnswerList(userid int64, pid int64) (userAnswer []UserAnswer, err error) {
	err = mysql.CreateMySQLClient(func(db *gorm.DB) error {

		err = db.Where("user_id = ? and p_id = ? ", userid, pid).Find(&userAnswer).Error
		return err
	})
	return userAnswer, err
}

// 用户刷题默认记录列表，支持分页
func (ua *UserAnswer) UserAnswerListAll(userID int64, pid int64, page int, pageSize int) (userAnswer []UserAnswer, err error) {
	err = mysql.CreateMySQLClient(func(db *gorm.DB) error {
		query := db.Where("user_id = ?", userID)

		if pid != 0 {
			query = query.Where("p_id = ?", pid)
		}

		// 如果页数或行数为0，则查询所有数据
		if page <= 0 || pageSize <= 0 {
			err = query.Find(&userAnswer).Error
		} else {
			// 添加分页
			offset := (page - 1) * pageSize
			err = query.Offset(offset).Limit(pageSize).Find(&userAnswer).Error
		}

		return err
	})

	return userAnswer, err
}

// 删除刷题记录
func (ua *UserAnswer) UserAnswerDelete(ids []int64, userID, pid int64) error {
	return mysql.CreateMySQLClient(func(db *gorm.DB) error {
		var err error
		if pid != 0 {
			// 如果指定了分类ID (pid)，则按分类ID删除，不考虑记录ID
			err = db.Where("user_id = ? AND p_id = ?", userID, pid).Delete(&UserAnswer{}).Error
		} else {
			// 如果没有指定分类ID，则按记录ID (ids) 删除
			err = db.Where("id IN (?) AND user_id = ?", ids, userID).Delete(&UserAnswer{}).Error
		}
		if err != nil {
			return err
		}
		return nil
	})
}
